//
//  HBTabBarItem.swift
//  sinaWeibo
//
//  Created by Beans on 16/7/6.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

//
class HBTabBarItem: UITabBarItem {

    override var badgeValue: String? {
        didSet {
            if badgeValue == nil {
                return
            }

            let tabBarController: UITabBarController? = valueForKey("_target") as? UITabBarController
                
            // 1. 遍历tabBar的子视图
            for childTabBarView in tabBarController!.tabBar.subviews {
                if childTabBarView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                    // 2. 再遍历UITabBarButton的子视图
                    for childTabBarButton in childTabBarView.subviews {
                        // 判断视图是否是 _UIBadgeView
                        if childTabBarButton.isKindOfClass(NSClassFromString("_UIBadgeView")!) {
                            printLog("找到了 _UIBadgeView")
                            // 3. 在继续遍历
                            for childBadgeView in childTabBarButton.subviews {
                                // 判断
                                if childBadgeView.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
                                    printLog("找到了")

                                    // 对私有属性进行赋值. KVC

                                    // 找到该类的属性
                                    var count: UInt32 = 0
                                    let result = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                    // 对属性进行遍历
                                    for i in 0..<count {
                                        // 1> 获取ivar
                                        let ivar = result[Int(i)]
                                        // 2> 获取属性的cString
                                        let cname = ivar_getName(ivar)
                                        // 3> 把cString -> String
                                        let name = String(CString: cname, encoding: NSUTF8StringEncoding)
                                        printLog(name)
                                    }

                                    // 通过KVC给属性赋值
                                    childBadgeView.setValue(UIImage(named: "main_badge"), forKey: "_image")
                                }
                            }
                        }
                    }
                }
            }

        }
    }

}
